# -*- coding: utf-8 -*-
'''
Created on 2014/02/28

@author: deadblue
'''
import base64
import hashlib
import hmac
import random
import time
import urllib
import urllib2

class OAuthConfig():
    API_KEY = None
    TOKEN = None
    SECERT = None

class OAuthClient():

    def get_timestamp(self):
        return int(time.time())
    def get_nonce(self):
        return '%x' % random.randint(999999, self.get_timestamp())
    def get_signature(self, method, url, params):
        data = []
        for k,v in params:
            data.append('%s=%s' % (k, urllib.quote(str(v))))
        base = '%s&%s&%s' % (method, urllib.quote(url, ''), urllib.quote('&'.join(sorted(data))))
        sign = hmac.new(OAuthConfig.SECERT, base, hashlib.sha1)
        return base64.b64encode(sign.digest())

    def get(self, url, params = []):
        # 处理参数
        if params is None: params = []
        params.append(('oauth_consumer_key', OAuthConfig.API_KEY))
        params.append(('oauth_token', OAuthConfig.TOKEN))
        params.append(('oauth_signature_method', 'HMAC-SHA1'))
        params.append(('oauth_timestamp', self.get_timestamp()))
        params.append(('oauth_nonce', self.get_nonce()))
        params.append(('oauth_signature', self.get_signature('GET', url, params)))
        # 构造请求
        req = urllib2.Request(self.__create_get_url__(url, params))
        req.add_header('Authorization', 'OAuth')
        resp = urllib2.urlopen(req)
        return resp.read()
    def __create_get_url__(self, url, params):
        data = list()
        for k,v in params:
            data.append("%s=%s" % (k, urllib.quote(str(v), '')))
        url = "%s?%s" % (url, '&'.join(data))
        return url

    def post(self, url, params = []):
        # 处理参数
        if params is None: params = []
        params.append(('oauth_consumer_key', OAuthConfig.API_KEY))
        params.append(('oauth_token', OAuthConfig.TOKEN))
        params.append(('oauth_signature_method', 'HMAC-SHA1'))
        params.append(('oauth_timestamp', self.get_timestamp()))
        params.append(('oauth_nonce', self.get_nonce()))
        params.append(('oauth_signature', self.get_signature('POST', url, params)))
        # 构造请求
        req = urllib2.Request(url, self.__create_post_data__(params))
        req.add_header('Authorization', 'OAuth')
        resp = urllib2.urlopen(req)
        return resp.read()
    def __create_post_data__(self, params):
        data = list()
        for k,v in params:
            data.append("%s=%s" % (k, urllib.quote(str(v), '')))
        return '&'.join(data)
